﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using Microsoft.Samples.Kinect.ControlsBasics;
using Microsoft.Kinect.Toolkit.Controls;
using Microsoft.Kinect.Toolkit;
using Microsoft.Kinect;
using System.IO;
using System.Xaml;
using KinectWpfDemo.Models;
using KinectWpfDemo.Properties;
using System.Collections.ObjectModel;

namespace KinectWpfDemo
{


    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static readonly DependencyProperty PageLeftEnabledProperty = DependencyProperty.Register(
    "PageLeftEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        public static readonly DependencyProperty PageRightEnabledProperty = DependencyProperty.Register(
            "PageRightEnabled", typeof(bool), typeof(MainWindow), new PropertyMetadata(false));

        private const double ScrollErrorMargin = 0.001;

        private const int PixelScrollByAmount = 20;

        private KinectSensorChooser sensorChooser;

        /// <summary>
        /// Gets the collection of paragraphs composing the content of the article.
        /// Changes to this property cause the PropertyChanged event to be signaled.
        /// </summary>
        public ObservableCollection<string> Paragraphs { get; private set; }

        /// <summary>
        /// Gets the collection of images associated with the article. 
        /// Changes to the paragraphs cause the CollectionChanged event to be signaled.
        /// </summary>
        public ObservableCollection<ImageSource> Images { get; private set; }

        public MainWindow()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(OnLoaded);

            this.UpdatePagingButtonState();
            scrollViewer.ScrollChanged += (o, e) => this.UpdatePagingButtonState();
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            // initialize the sensor chooser and UI
            this.sensorChooser = new KinectSensorChooser();
            this.sensorChooser.KinectChanged += new EventHandler<KinectChangedEventArgs>(KinectSensorsOnStatusChanged);
            this.sensorChooserUi.KinectSensorChooser = sensorChooser;
            this.sensorChooser.Start();

            //GetImages();
            GetImages2("/Images/");
        }

        void GetImages2(string path)
        {
            this.wrapPanel.Children.Clear();
            int iImageCount = Int16.Parse(KinectWpfDemo.Properties.Resources.ImageCount);
            string strImageExt = KinectWpfDemo.Properties.Resources.ImageExt;
            for (int i = 1; i < iImageCount + 1; i++)
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = (iImageCount < 10) ? new Uri(string.Format("{0}pic0{1}{2}", path.ToString(), i.ToString(), strImageExt), UriKind.Relative) : new Uri(string.Format("{0}pic{1}{2}", path.ToString(), i.ToString(), strImageExt), UriKind.Relative);
                //bi.UriSource = new Uri("/Images/pic01.jpg", UriKind.Relative);
                bi.EndInit();
                var image = new Image();
                image.Source = bi;
                image.MouseDown += new MouseButtonEventHandler(image_MouseDown);
                this.wrapPanel.Children.Add(image);
            }
        }

        void image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var image = (Image)e.Source;
            //var ShowImage = new ShowImage(image.Source);
            var ShowImage = new ShowImage(sender, e);
            ShowImage.Width = 1280;
            ShowImage.Height = 720;
            this.Grid1.Children.Add(ShowImage);
            e.Handled = true;
        }

        void GetImages()
        {
            this.wrapPanel.Children.Clear();
            for (var index = 0; index < 50; ++index)
            {
                var image = new Image();
                BitmapImage bi3 = new BitmapImage();
                bi3.BeginInit();
                bi3.UriSource = new Uri(index % 2 == 0 ? "Images/garu.png" : "Images/pucca.png", UriKind.Relative);
                bi3.EndInit();
                //image.Stretch = Stretch.Fill;
                //image.Height = 128; image.Width = 128;
                image.Source = bi3;
                this.wrapPanel.Children.Add(image);

                //var button = new KinectTileButton { Label = (index + 1).ToString(CultureInfo.CurrentCulture) };
                //this.wrapPanel.Children.Add(button);
            }
        }

        void KinectSensorsOnStatusChanged(object sender, KinectChangedEventArgs args)
        {
            bool isError = false;
            if (args.OldSensor != null)
            {
                try
                {
                    args.OldSensor.DepthStream.Range = DepthRange.Default;
                    args.OldSensor.SkeletonStream.EnableTrackingInNearRange = false;
                    args.OldSensor.DepthStream.Disable();
                    args.OldSensor.SkeletonStream.Disable();
                }
                catch (InvalidOperationException)
                {
                    // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
                    // E.g.: sensor might be abruptly unplugged.
                    isError = true;
                }
            }

            if (args.NewSensor != null)
            {
                try
                {
                    args.NewSensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
                    args.NewSensor.SkeletonStream.Enable();

                    try
                    {
                        args.NewSensor.DepthStream.Range = DepthRange.Near;
                        args.NewSensor.SkeletonStream.EnableTrackingInNearRange = true;
                        args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated;
                    }
                    catch (InvalidOperationException)
                    {
                        // Non Kinect for Windows devices do not support Near mode, so reset back to default mode.
                        args.NewSensor.DepthStream.Range = DepthRange.Default;
                        args.NewSensor.SkeletonStream.EnableTrackingInNearRange = false;
                        args.NewSensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Default;
                    }
                }
                catch (InvalidOperationException)
                {
                    // KinectSensor might enter an invalid state while enabling/disabling streams or stream features.
                    // E.g.: sensor might be abruptly unplugged.
                    isError = true;
                }

                try
                {
                    if (!isError)
                        kinectRegion.KinectSensor = args.NewSensor;
                }
                catch (Exception)
                { throw; }



            }






        }

        private void wrapPanel_Click(object sender, RoutedEventArgs e)
        {
            var button = (KinectTileButton)e.OriginalSource;
            var selectionDisplay = new SelectionDisplay(button.Content as string);
            selectionDisplay.Width = 1280;
            selectionDisplay.Height = 720;
            this.Grid1.Children.Add(selectionDisplay);
            e.Handled = true;
        }


        /// <summary>
        /// Handle a button click from the wrap panel.
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void KinectTileButtonClick(object sender, RoutedEventArgs e)
        {
            var button = (KinectTileButton)e.OriginalSource;
            var selectionDisplay = new SelectionDisplay(button.Label as string);
            this.kinectRegionGrid.Children.Add(selectionDisplay);
            e.Handled = true;
        }

        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.sensorChooser.Stop();
        }


        #region KinectHoverButton Methods

        /// <summary>
        /// CLR Property Wrappers for PageLeftEnabledProperty
        /// </summary>
        public bool PageLeftEnabled
        {
            get
            {
                return (bool)GetValue(PageLeftEnabledProperty);
            }

            set
            {
                this.SetValue(PageLeftEnabledProperty, value);
            }
        }

        /// <summary>
        /// CLR Property Wrappers for PageRightEnabledProperty
        /// </summary>
        public bool PageRightEnabled
        {
            get
            {
                return (bool)GetValue(PageRightEnabledProperty);
            }

            set
            {
                this.SetValue(PageRightEnabledProperty, value);
            }
        }

        /// <summary>
        /// Handle paging right (next button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageRightButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset + PixelScrollByAmount);
        }

        /// <summary>
        /// Handle paging left (previous button).
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private void PageLeftButtonClick(object sender, RoutedEventArgs e)
        {
            scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - PixelScrollByAmount);
        }

        /// <summary>
        /// Change button state depending on scroll viewer position
        /// </summary>
        private void UpdatePagingButtonState()
        {
            this.PageLeftEnabled = scrollViewer.HorizontalOffset > ScrollErrorMargin;
            this.PageRightEnabled = scrollViewer.HorizontalOffset < scrollViewer.ScrollableWidth - ScrollErrorMargin;
        }

        #endregion


    }
}
